package com.lu.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lu.common.vo.PageResponse;
import com.lu.sys.entity.*;
import com.lu.sys.entity.vo.CourseDTO;
import com.lu.sys.entity.vo.CourseDelDTO;
import com.lu.sys.mapper.ChapterMapper;
import com.lu.sys.mapper.CourseMapper;
import com.lu.sys.mapper.FileMapper;
import com.lu.sys.service.ICourseService;
import com.lu.sys.mapper.SectionMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import static com.lu.common.utils.CommonUtils.setLikeWrapper;

@Service
@RequiredArgsConstructor
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements ICourseService {

    @Resource
    private CourseMapper courseMapper;

    @Resource
    private FileMapper fileMapper;

    @Resource
    private ChapterMapper chapterMapper;

    @Resource
    private SectionMapper sectionMapper;

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public int addCourse(CourseDTO courseDTO) {
        //存课程信息
        if (courseDTO.getCourse()==null){
            return 0;
        }
        Course course = courseDTO.getCourse();
        int courseId = courseMapper.insertSelective(course);
        updateFile(course.getCoverFileId(),course.getId(),1);
        //存章节信息
        if (CollectionUtils.isEmpty(courseDTO.getCharacterList())){
            return 0;
        }
        List<Chapter> chapterList = courseDTO.getCharacterList();
        for (Chapter chapter : chapterList) {
            chapter.setCourseId(course.getId());
            int i = chapterMapper.insertSelective(chapter);
            if (!CollectionUtils.isEmpty(chapter.getSectionList())){
                for (Section section : chapter.getSectionList()) {
                    section.setChapterId(chapter.getId());
                    sectionMapper.insertSelective(section);
                    if (!CollectionUtils.isEmpty(section.getSectionFiles())){
                        for (File sectionFile : section.getSectionFiles()) {
                            updateFile(sectionFile.getId(),section.getId(),sectionFile.getFileType());
                        }
                    }
                }
            }
        }
        return 1;
    }

    @Override
    public PageResponse<CourseDTO> getCourseList(String title, Long pageNo, Long pageSize) {
        QueryWrapper<Course> wrapper = new QueryWrapper<>();
        setLikeWrapper(wrapper, Collections.singletonMap("title", title));

        IPage<Course> iPage = courseMapper.selectPage(new Page<>(pageNo, pageSize), wrapper);
        List<Course> courses = iPage.getRecords();
        // 封装成传给前端的数据类型
        List<CourseDTO> courseDTOList = new ArrayList<>();
        for (Course course : courses) {
            //查找课程封面id
            List<File> fileList = fileMapper.selectByTypeId(1,course.getId());
            if (!CollectionUtils.isEmpty(fileList)){
                course.setCoverFileId(fileList.get(0).getId());
                course.setCoverFileName(fileList.get(0).getFileName());
            }
            // 创建vo对象
            CourseDTO courseDTO = new CourseDTO();
            // 设置属性
            courseDTO.setCourse(course);
            //根据课程id查找所有的章节
            List<Chapter> chapterList = chapterMapper.selectChapterListByCourseId(course.getId());
            //查找所有章节中的小节
            for (Chapter chapter : chapterList) {
                List<Section> sectionList = sectionMapper.selectSectionByChapter(chapter.getId());
                for (Section section : sectionList) {
                    List<File> sectionFiles = fileMapper.selectByTypeId(0, section.getId());
                    section.setSectionFiles(sectionFiles);
                }
                chapter.setSectionList(sectionList);
            }
            courseDTO.setCharacterList(chapterList);
            // 加入list中
            courseDTOList.add(courseDTO);
        }
        return PageResponse.<CourseDTO>builder().data(courseDTOList).total(iPage.getTotal()).build();
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public int updateCourse(CourseDTO courseDTO) {
        //更新课程信息
        if (courseDTO.getCourse()==null){
            return 0;
        }
        Course course = courseDTO.getCourse();
        courseMapper.updateByPrimaryKeySelective(course);
        updateFile(course.getCoverFileId(),course.getId(),1);
        //更新章节信息
        if (CollectionUtils.isEmpty(courseDTO.getCharacterList())){
            return 0;
        }
        List<Chapter> chapterList = courseDTO.getCharacterList();
        for (Chapter chapter : chapterList) {
            chapterMapper.updateByPrimaryKeySelective(chapter);
            if (!CollectionUtils.isEmpty(chapter.getSectionList())){
                for (Section section : chapter.getSectionList()) {
                    section.setChapterId(chapter.getId());
                    sectionMapper.updateByPrimaryKeySelective(section);
                    //查询所有的章节文件并删除
                    List<File> fileList = fileMapper.selectBySectionId(section.getId());
                    for (File file : fileList) {
                        fileMapper.deleteByPrimaryKey(file.getId());
                    }
                    if (!CollectionUtils.isEmpty(section.getSectionFiles())){
                        for (File sectionFile : section.getSectionFiles()) {
                            updateFile(sectionFile.getId(),section.getId(),sectionFile.getFileType());
                        }
                    }
                }
            }
        }
        //更新小节信息
        return 1;
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public int deleteCourse(CourseDelDTO courseDelDTO) {
        Integer id = courseDelDTO.getId();
        //判断是课程，章节还是小节
        if (courseDelDTO.getType()!=null){
            switch (courseDelDTO.getType()){
                case 1 :
                   courseMapper.deleteByPrimaryKey(id);
//                    Course course = chapterMapper.selectByPrimaryKey(id);
//                    chapterMapper.deleteByCourseId(id);
                    break; //可选
                case 2 :
                    chapterMapper.deleteByPrimaryKey(id);
                    break; //可选
                case 3 :
                    sectionMapper.deleteByPrimaryKey(id);
                    break; //可选
                //你可以有任意数量的case语句
                default : //可选
                    return 0;
            }
        }
        return 1;
    }

    public void updateFile(Integer fileId,Integer fileTypeId,Integer fileType){
        File file = new File();
        file.setFileDel(0);
        file.setId(fileId);
        file.setFileTypeId(fileTypeId);
        file.setFileType(fileType);
        fileMapper.updateByPrimaryKeySelective(file);
    }
}
